package com.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${jujiaoyuan.cos.file-path}")
    String uploadPath;
    @Value("${jujiaoyuan.cos.bucket}")
    String bucket;
    @Autowired
    COSClient cosClient;


    @PostMapping("/upload")
    public String uploadFile(@RequestParam("image") MultipartFile image) throws IOException {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicReadWrite);
        cosClient.createBucket(createBucketRequest);
        String imageName = image.getName();
        String key = uploadPath + imageName;
        InputStream inputStream = null;
        PutObjectResult putObjectResult;
        try {
            inputStream = image.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, inputStream, null);
            putObjectResult = cosClient.putObject(putObjectRequest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            assert inputStream != null;
            inputStream.close();
        }

        return putObjectResult.getRequestId();

    }

}
